package cs236369.hw5;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.ServletContext;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class WSPostsResource extends ServerResource {
	@Get
	public String represent() {
		double latPos = Double.parseDouble(getRequest().getAttributes().get("latVal").toString());
		double lngPos = Double.parseDouble(getRequest().getAttributes().get("lngVal").toString());
		double distance = Double.parseDouble(getRequest().getAttributes().get("distVal").toString());

		// get servlet context
		ServletContext sc = (ServletContext) getContext().getAttributes().get( "org.restlet.ext.servlet.ServletContext" );;
		OutputStream os = new ByteArrayOutputStream();
		// create a list of all posts in range
		ArrayList<Post> postsList = DBConnection.searchPosts(latPos, lngPos, distance, 0, null);
		postsList.addAll(DBConnection.searchPosts(latPos, lngPos, distance, 1, null));
		//convert to JSON
		XALANconverter.convertPostsToJSON(XMLGenerator.getPostsXMLasInputStream(postsList, sc), os, sc);
		String json = os.toString();
		System.out.println(json);
		return json;
	} 
	//another way: String json = org.json.XML.toJSONObject(XMLGenerator.getPostsXMLasString()).toString();
}
